//
//  LTF EntertainmentView.m
//  NeteaseNews
//
//  Created by liutaifeng on 16/4/26.
//  Copyright © 2016年 liutaifeng. All rights reserved.
//

#import "LTFEntertainmentView.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "LTFExclusiveModel.h"
#import "LTFFirstTableViewCell.h"
#import "LTFThirdTableViewCell.h"
#import "LTFSecondTableViewCell.h"
#import "LTFADCollectionViewCell.h"
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height


@interface LTFEntertainmentView ()
<
 UITableViewDelegate,
 UITableViewDataSource,
 UICollectionViewDataSource,
 UICollectionViewDelegate
>
@property (nonatomic, retain) NSMutableArray *tableViewArray;
@property (nonatomic, retain) UIView *headView;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *adArray;
@property (nonatomic, retain) UICollectionView *adCollectionView;
@property (nonatomic, retain) UIPageControl *page;
@end

@implementation LTFEntertainmentView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
    }
    return self;
}
- (void)createView {
    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.frame style:UITableViewStylePlain];
    [self addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tag = 1009;
    //头视图
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    [self addSubview:_headView];
    [_headView release];
    
    _tableView.tableHeaderView = _headView;
    //轮播图
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(WIDTH, HEIGHT / 3);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    self.adCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3) collectionViewLayout:layout];
    [_headView addSubview:_adCollectionView];
    _adCollectionView.delegate = self;
    _adCollectionView.dataSource = self;
    [_adCollectionView registerClass:[LTFADCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LTFADCollectionViewCell class])];
    _adCollectionView.pagingEnabled = YES;
    
    
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH - 30, HEIGHT / 3 / 5 * 4, 20, 20)];
    [_headView addSubview:_page];
    [_page release];
    
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.contentOffset.x == 3 * WIDTH) {
        collectionView.contentOffset = CGPointMake(WIDTH, 0);
    }
    if (collectionView.contentOffset.x == 0) {
        collectionView.contentOffset = CGPointMake(WIDTH * 2, 0);
    }
    self.page.currentPage = collectionView.contentOffset.x / WIDTH - 1;    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LTFExclusiveModel *model = self.adArray[indexPath.row];
    if (indexPath.row == 2) {
        [self.delegate sendEntertainmentAddress:model.docid];
    }
    else if (indexPath.row == 1){
        [self.delegate sendEntertainmentAddress:model.postid];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.adArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LTFADCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LTFADCollectionViewCell class]) forIndexPath:indexPath];
    LTFExclusiveModel *model = self.adArray[indexPath.row];
    [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.titltLabel.text = model.title;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFExclusiveModel *model = self.tableViewArray[indexPath.row];
    if (model.imgextra == nil) {
        if (model.imgType == 0) {
            static NSString *firstReuse = @"firstReuse";
            LTFFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstReuse];
            if (!cell) {
                cell = [[[LTFFirstTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:firstReuse] autorelease];
            }
            //图片
            [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
            //标题
            cell.titleLabel.text = model.title;
            //内容
            
            cell.contentLabel.text = model.digest;
            
            //跟帖
            if (model.TAGS != nil) {
                cell.countLabel.text = model.TAGS;
                cell.countLabel.textColor = [UIColor blueColor];
                
                cell.countLabel.layer.borderWidth = 1;
                cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
                cell.countLabel.font = [UIFont systemFontOfSize:13];
                cell.countLabel.textAlignment = 1;
            } else {
                cell.countLabel.textColor = [UIColor grayColor];
                cell.countLabel.layer.borderWidth = 0;
                cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
                cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
            }
            return cell;
        }
        else {
            static NSString *secondReuse = @"secondReuse";
            LTFSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:secondReuse];
            if (!cell) {
                cell = [[[LTFSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:secondReuse] autorelease];
            }
            //图片
            [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
            //标题
            cell.titleLabel.text = model.title;
            //内容
            
                cell.contentLabel.text = model.digest;
            
            //跟帖数
            if (model.TAGS != nil) {
                cell.countLabel.text = model.TAGS;
                cell.countLabel.textColor = [UIColor blueColor];
                
                cell.countLabel.layer.borderWidth = 1;
                cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
                cell.countLabel.font = [UIFont systemFontOfSize:13];
                cell.countLabel.textAlignment = 1;
            } else {
                cell.countLabel.textColor = [UIColor grayColor];
                cell.countLabel.layer.borderWidth = 0;
                cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
                cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
            }
            
            return cell;
        }
    }
    else {
        static NSString *thirdReuse = @"thirdReuse";
        LTFThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:thirdReuse];
        if (!cell) {
            cell = [[[LTFThirdTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:thirdReuse] autorelease];
        }
        cell.titleLabel.text = model.title;
        
        cell.countLabel.textColor = [UIColor grayColor];
        if (model.TAGS != nil) {
            cell.countLabel.text = model.TAGS;
            cell.countLabel.textColor = [UIColor blueColor];
            
            cell.countLabel.layer.borderWidth = 1;
            cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
            cell.countLabel.font = [UIFont systemFontOfSize:13];
            cell.countLabel.textAlignment = 1;
        } else {
            cell.countLabel.textColor = [UIColor grayColor];
            cell.countLabel.layer.borderWidth = 0;
            cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
            cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
        }
        
        [cell.firstImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        [cell.secondImageView setImageWithURL:[NSURL URLWithString:[model.imgextra firstObject][@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        [cell.thirdImageView setImageWithURL:[NSURL URLWithString:[model.imgextra lastObject][@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFExclusiveModel *model = self.tableViewArray[indexPath.row];
    if (model.imgextra == nil) {
        if (model.imgType == 0) {
            return 130;
        } else {
            return 240;
        }
    } else {
        return 180;
    }
}

- (void)setString:(NSString *)string {
    if (_string != string) {
        [_string release];
        _string = [string retain];
        [self createData];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFExclusiveModel *model = self.tableViewArray[indexPath.row];
    [self.delegate sendAddress:model.docid];
}
- (void)createData {
    self.tableViewArray = [NSMutableArray array];
    self.adArray = [NSMutableArray array];
    NSString *str = [NSString string];
        str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/0-20.html", self.string];
    
    //请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dictionary = responseObject;
        NSArray *array = [NSArray array];
        
            array = [dictionary objectForKey:self.string];
        
        
        self.tableViewArray = [LTFExclusiveModel BaseModelByArray:array];
        
        if (self.tableViewArray.count != 0) {
            LTFExclusiveModel *model = self.tableViewArray[0];
            [self.adArray addObject:model];
            for (NSDictionary *dic in model.ads) {
                LTFExclusiveModel *smallModel = [[LTFExclusiveModel new] autorelease];
                [smallModel setValuesForKeysWithDictionary:dic];
                [self.adArray addObject:smallModel];
            }
            if (self.adArray.count == 1) {
                NSString *string = [NSString stringWithFormat:@"http://g1.163.com/madrs?app=7A16FBB6&platform=android&category=%@&location=10,11,20,21,22,23,24,25&timestamp=1461673743860&uid=3yL/L2x9wTpSrIEs0YFgpKP3mOf79uniXcOgfSbt7pHX8qhGQ6b5hlY8H8B/VE1nvt7xNR6nz3xvROp2NpyNphB1EdcyeQrOCPndphukv8UcCSM2sEWa7pGtCqn6gn0Be71nTXvqnnYxZrJDMIpZlct00c+zLjAKGcQQdxi4Cm30GNTuXcZ1fGh64pV2pvUH8KTP7xoz9lJabnrncpcmSSB8iPjqpC7Ci7QhHR8kaLojMsDOVZ+C90JtUxkNRSeOXnbB3qzTz6erLdiVsiNxBA==", self.string];
                
                AFHTTPSessionManager *adManager = [AFHTTPSessionManager manager];
                [adManager GET:string parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSArray *array = responseObject;
                    NSDictionary *dic = [array lastObject];
                    NSArray *adArray = dic[@"ads"];
                    for (NSDictionary *dic in adArray) {
                        LTFExclusiveModel *smallModel = [[LTFExclusiveModel new] autorelease];
                        [smallModel setValuesForKeysWithDictionary:dic];
                        [self.adArray addObject:smallModel];
                    }
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    
                }];
                
                
            }
            [self.adArray addObject:[self.adArray firstObject]];
            [self.adArray insertObject:self.adArray[1] atIndex:0];
            //轮播图数组adarray
            [self.adCollectionView reloadData];
            _adCollectionView.contentOffset = CGPointMake(WIDTH, 0);
            self.page.numberOfPages = self.adArray.count - 2;
            }
            [self.tableViewArray removeObjectAtIndex:0];
            [self.tableView reloadData];
            self.tableView.contentOffset = CGPointMake(0, 0);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
